import React, { useContext } from 'react';
import { RenderDropableWidget, usePlugin, useLayouts } from '@inbiz/react';
import { TreeNode } from '@inbiz/core';
import cls from 'classnames';
import {
  useInbizPrefixCls,
  useIsDesigner,
  useToolbar,
} from '../../hooks';
import { InBizTableCtx } from '../../context';


interface TableTopProps {
  searchNode: React.ReactNode;
  viewMode?:string;
}
const TableTop = (props: TableTopProps) => {
  const { buttonRegion, buttonPosition,viewMode } = useContext(InBizTableCtx);
  const isDesignable = useIsDesigner();
  const toolbar = useToolbar();
  const btnGroupDesignable = useInbizPrefixCls('table-designable-btn-group');
  const btnGroupRight = 'btn-group-right';
  let queryPlugin: any;
  let btnGroupPlugin: any = undefined;
  if (isDesignable) {
    btnGroupPlugin = usePlugin('Table.BtnGroup');
    const { children = [] } = btnGroupPlugin[0] || {};
    const node = children.find((node: any) => node.props['x-component'] == 'Table.Toolbar');
    if (!node && toolbar?.actions?.length) {
      const column = new TreeNode({
        componentName: 'Field',
        props: {
          type: 'void',
          'x-component': 'Table.Toolbar',
        },
      });
      btnGroupPlugin[0]?.append(column);
    }
    if (node && !toolbar?.actions?.length) {
      node.remove();
    }
  } else {
    queryPlugin = useLayouts('Table.Query');
    btnGroupPlugin = useLayouts('Table.BtnGroup');
  }
  return (
    <div className='inbiz-table-top-container'>
      {isDesignable ? (
        <>
          {props.searchNode}
          <div
            className={
              buttonPosition == 'left'
                ? cls([btnGroupDesignable])
                : cls([btnGroupDesignable, btnGroupRight])
            }
            style={{ display: buttonRegion ? 'block' : 'none' }}
          >
            <RenderDropableWidget node={btnGroupPlugin} pluginName={'Table.BtnGroup'} />
          </div>
        </>
      ) : (
        <>
          {viewMode!='look'&&queryPlugin && queryPlugin[0]?.schema?.properties && props.searchNode}
          {btnGroupPlugin && btnGroupPlugin[0]?.schema?.properties &&(
            <div
              className="inbiz-table-btn-group-container"
              style={{ display: buttonRegion ? 'flex' : 'none' }}
            >
              {btnGroupPlugin && btnGroupPlugin.length && (
                <RenderDropableWidget pluginName={'Table.BtnGroup'} />
              )}
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default React.memo(TableTop);
